<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="所属学科组" prop="deptId">
        <el-select v-model="formData.deptId" placeholder="请选择所属学科组" clearable filterable>
          <el-option
            v-for="subjectGroup in subjectGroupList"
            :key="subjectGroup.groupId"
            :label="subjectGroup.groupName"
            :value="subjectGroup.groupId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属学校" prop="schoolId">
        <el-select v-model="formData.schoolId" placeholder="请选择所属学校" clearable filterable>
          <el-option
            v-for="school in schoolList"
            :key="school.schoolId"
            :label="school.schoolName"
            :value="school.schoolId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="专业名称" prop="majorName">
        <el-input v-model="formData.majorName" placeholder="请输入专业名称" />
      </el-form-item>
      <el-form-item label="专业编码" prop="majorCode">
        <el-input v-model="formData.majorCode" placeholder="请输入专业编码" />
      </el-form-item>
      <el-form-item label="学制年限" prop="duration">
        <el-input v-model="formData.duration" placeholder="请输入学制年限" />
      </el-form-item>
      <el-form-item label="总学分要求" prop="totalCredits">
        <el-input v-model="formData.totalCredits" placeholder="请输入总学分要求" />
      </el-form-item>
      <el-form-item label="专业负责人" prop="majorDirectorId">
        <el-select v-model="formData.majorDirectorId" placeholder="请选择专业负责人" clearable filterable>
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.teacherId"
            :label="`${teacher.teacherName}(${teacher.teacherNo || '无工号'})`"
            :value="teacher.teacherId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="专业描述" prop="description">
        <Editor v-model="formData.description" height="150px" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择状态">
          <el-option label="正常" :value="0" />
          <el-option label="停用" :value="1" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { MajorApi, Major } from '@/api/ao/major'
import { SubjectGroupApi, SubjectGroup } from '@/api/ao/subjectgroup'
import { SchoolApi, School } from '@/api/ao/school'
import { TeacherApi, Teacher } from '@/api/ao/teacher'

/** 专业信息 表单 */
defineOptions({ name: 'MajorForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  majorId: undefined,
  deptId: undefined,
  schoolId: undefined,
  majorName: undefined,
  majorCode: undefined,
  duration: undefined,
  totalCredits: undefined,
  majorDirectorId: undefined,
  description: '', // 设置为空字符串而不是 undefined，避免富文本编辑器报错
  status: undefined,
})
const formRules = reactive({
  deptId: [{ required: true, message: '所属学科组不能为空', trigger: 'change' }],
  schoolId: [{ required: true, message: '所属学校不能为空', trigger: 'change' }],
  majorName: [{ required: true, message: '专业名称不能为空', trigger: 'blur' }],
  majorCode: [{ required: true, message: '专业编码不能为空', trigger: 'blur' }],
  duration: [{ required: true, message: '学制年限不能为空', trigger: 'blur' }],
  majorDirectorId: [{ required: false, message: '专业负责人不能为空', trigger: 'change' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref

// 学科组、学校和教师列表
const subjectGroupList = ref<SubjectGroup[]>([])
const schoolList = ref<School[]>([])
const teacherList = ref<Teacher[]>([])

/** 加载学科组、学校和教师列表 */
const loadSelectData = async () => {
  try {
    const [subjectGroupData, schoolData, teacherData] = await Promise.all([
      SubjectGroupApi.getSimpleSubjectGroupList(),
      SchoolApi.getSimpleSchoolList(),
      TeacherApi.getSimpleTeacherList()
    ])
    subjectGroupList.value = subjectGroupData
    schoolList.value = schoolData
    teacherList.value = teacherData
  } catch (error) {
    console.error('加载下拉框数据失败:', error)
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 加载下拉框数据
  await loadSelectData()

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await MajorApi.getMajor(id)
      // 确保 description 字段不为 null，避免富文本编辑器报错
      formData.value = {
        ...data,
        description: data.description || ''
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as Major
    if (formType.value === 'create') {
      await MajorApi.createMajor(data)
      message.success(t('common.createSuccess'))
    } else {
      await MajorApi.updateMajor(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    majorId: undefined,
    deptId: undefined,
    schoolId: undefined,
    majorName: undefined,
    majorCode: undefined,
    duration: undefined,
    totalCredits: undefined,
    majorDirectorId: undefined,
    description: '', // 设置为空字符串而不是 undefined，避免富文本编辑器报错
    status: undefined,
  }
  formRef.value?.resetFields()
}
</script>